package com.hellobike.haxing.modules.pms.purchaseSend.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.system.vo.LoginUser;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.pms.purchaseSend.entity.TPurchasePrintSku;
import com.hellobike.haxing.modules.pms.purchaseSend.entity.TPurchaseSend;
import com.hellobike.haxing.modules.pms.purchaseSend.service.ITPurchasePrintSkuService;
import com.hellobike.haxing.modules.pms.purchaseSend.service.ITPurchaseSendService;
import com.hellobike.haxing.modules.purchase.entity.TPurchaseOrder;
import com.hellobike.haxing.modules.purchase.entity.TPurchaseOrderDetail;
import com.hellobike.haxing.modules.purchase.enums.OrderState;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseOrderService;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseProService;
import com.hellobike.haxing.modules.supplier.entity.TSupplierInfo;
import com.hellobike.haxing.modules.supplier.service.ITSupplierInfoService;
import com.hellobike.haxing.modules.supplier.util.BeanUtils;
import com.hellobike.haxing.modules.supplier.util.Constant;
import com.hellobike.haxing.modules.supplier.util.Convert;
import com.hellobike.haxing.modules.wms.utils.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.stream.Collectors;
 /**
 * @Description: t_purchase_print_sku
 * @Author: haxing-boot
 * @Date:   2020-02-18
 * @Version: V1.0
 */
@RestController
@RequestMapping("/purchaseSend/tPurchasePrintSku")
@Slf4j
public class TPurchasePrintSkuController extends BaseController<TPurchasePrintSku, ITPurchasePrintSkuService> {
	@Autowired
	private ITPurchasePrintSkuService tPurchasePrintSkuService;
	 @Autowired
	 private ITPurchaseSendService tPurchaseSendService;
	 @Autowired
	 private ITPurchaseOrderService tPurchaseOrderService;
	 @Autowired
	 private ITPurchaseProService tPurchaseProService;
	 @Autowired
	 private ITSupplierInfoService tSupplierInfoService;

	 /**
	 * 分页列表查询
	 *
	 * @param tPurchasePrintSku
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "t_purchase_print_sku-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TPurchasePrintSku tPurchasePrintSku,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TPurchasePrintSku> queryWrapper = QueryGenerator.initQueryWrapper(tPurchasePrintSku, req.getParameterMap());
		Long supplierId = getSupplierId();
		if(supplierId == null){
			return Result.error("用户不存在");
		}
		queryWrapper.eq("supplier_id", supplierId);
		Page<TPurchasePrintSku> page = new Page<TPurchasePrintSku>(pageNo, pageSize);
		IPage<TPurchasePrintSku> pageList = tPurchasePrintSkuService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	 private Long getSupplierId(){
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if(sysUser == null){
			 return null;
		 }
		 QueryWrapper<TSupplierInfo> tSupplierInfoQueryWrapper = new QueryWrapper<>();
		 tSupplierInfoQueryWrapper.eq("mobile", sysUser.getPhone());
		 TSupplierInfo tSupplierInfo = tSupplierInfoService.getOne(tSupplierInfoQueryWrapper);
		 if(tSupplierInfo == null){
			 return null;
		 }
		 return tSupplierInfo.getId();
	 }
	
	/**
	 *   添加
	 *
	 * @param tPurchasePrintSku
	 * @return
	 */
	@AutoLog(value = "t_purchase_print_sku-添加",operateType=2)
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TPurchasePrintSku tPurchasePrintSku) {
		tPurchasePrintSkuService.save(tPurchasePrintSku);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param tPurchasePrintSku
	 * @return
	 */
	@AutoLog(value = "t_purchase_print_sku-编辑",operateType=3)
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody TPurchasePrintSku tPurchasePrintSku) {
		tPurchasePrintSkuService.updateById(tPurchasePrintSku);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "t_purchase_print_sku-删除",operateType=4)
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		tPurchasePrintSkuService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "t_purchase_print_sku-批量删除",operateType=4)
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tPurchasePrintSkuService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
		TPurchasePrintSku tPurchasePrintSku = tPurchasePrintSkuService.getById(id);
		if(tPurchasePrintSku==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(tPurchasePrintSku);
	}


	 /**
	  *  编辑
	  *
	  * @param json
	  * @return
	  */
	 @AutoLog(value = "t_purchase_print_sku-打印发货单",operateType=3)
	 @PutMapping(value = "/printSend")
	 public Result<?> printSend(@RequestBody JSONObject json) {
		 if(json == null){
			 return Result.ok("参数为空!");
		 }
		 TPurchaseOrder tPurchaseOrder = JSONObject.toJavaObject(json, TPurchaseOrder.class);
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // 保存发货单信息
		 TPurchaseSend send = new TPurchaseSend();
		 BeanUtils.copyProperties(tPurchaseOrder,send);
		 send.setPurchaseCode(tPurchaseOrder.getOrderCode());
		 send.setState(tPurchaseOrder.getCarState());
		 send.setSendCode(Convert.getSendCodeByTime());
		 send.setCreateBy(sysUser.getId());
		 send.setDeleted(0);


		 // 保存发货单商品信息
		 if(ListUtil.isNotEmpty(tPurchaseOrder.getTPurchaseOrderDetails())){
			 tPurchaseOrder.getTPurchaseOrderDetails().forEach(
					 item ->{
						 TPurchasePrintSku tPurchasePrintSku = new TPurchasePrintSku();
						 BeanUtils.copyProperties(item,tPurchasePrintSku);
						 tPurchasePrintSku.setPrintCode(send.getSendCode());
						 tPurchasePrintSku.setType(Constant.PRINT_SEND);
						 tPurchasePrintSku.setSkuVolume(item.getPurchaseVolume());
						 tPurchasePrintSku.setDeleted(0);
						 tPurchasePrintSkuService.save(tPurchasePrintSku);
					 }
			 );
			 send.setSkuTotalVolume(tPurchaseOrder.getTPurchaseOrderDetails().stream().mapToInt(TPurchaseOrderDetail::getPurchaseVolume).sum());

			 tPurchaseProService.genAsn(tPurchaseOrder.getTPurchaseOrderDetails(), tPurchaseOrder, send, sysUser.getId());
		    }
		 tPurchaseSendService.save(send);

		 // 修改订单状态为已经发货
		 TPurchaseOrder updateDo = new TPurchaseOrder();
		 updateDo.setId(tPurchaseOrder.getId());
		 updateDo.setState(OrderState.ORDER_STATE_5.getIndex());
		 tPurchaseOrderService.updateById(updateDo);

		 return Result.ok("编辑成功!");
	 }


	 /**
	  *  编辑
	  *
	  * @param json
	  * @return
	  */
	 @AutoLog(value = "t_purchase_print_sku-打印商品",operateType=3)
	 @PutMapping(value = "/printSku")
	 public Result<?> printSku(@RequestBody JSONObject json) {

		 if(json == null){
			 return Result.ok("参数为空!");
		 }
		 TPurchaseOrder tPurchaseOrder = JSONObject.toJavaObject(json, TPurchaseOrder.class);

		 // 保存商品打印信息
		 if(ListUtil.isNotEmpty(tPurchaseOrder.getTPurchaseOrderDetails())){
			 tPurchaseOrder.getTPurchaseOrderDetails().forEach(
					 item ->{
						 TPurchasePrintSku tPurchasePrintSku = new TPurchasePrintSku();
						 BeanUtils.copyProperties(item,tPurchasePrintSku);
						 tPurchasePrintSku.setPrintCode(tPurchaseOrder.getOrderCode());
						 tPurchasePrintSku.setSkuVolume(item.getPurchaseVolume());
						 tPurchasePrintSku.setBarcode(item.getBarcode());
						 tPurchasePrintSku.setDimensionValues(item.getDimensionValues());
						 tPurchasePrintSku.setType(Constant.PRINT_SKU);
						 tPurchasePrintSku.setDeleted(0);
						 tPurchasePrintSkuService.save(tPurchasePrintSku);
					 }
			 );
		 }

		 // 修改订单状态为已经发货
		 TPurchaseOrder updateDo = new TPurchaseOrder();
		 updateDo.setId(tPurchaseOrder.getId());
		 if(tPurchaseOrder.getState() != null && tPurchaseOrder.getState() < OrderState.ORDER_STATE_4.getIndex()) {
			 updateDo.setState(OrderState.ORDER_STATE_4.getIndex());
		 }
		 tPurchaseOrderService.updateById(updateDo);
		 return Result.ok("编辑成功!");
	 }


	 /**
    * 导出excel
    *
    * @param request
    * @param tPurchasePrintSku
    */
    @AutoLog(value = "t_purchase_print_sku-导出excel",operateType=6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TPurchasePrintSku tPurchasePrintSku) {
        return super.exportXls(request, tPurchasePrintSku, TPurchasePrintSku.class, "t_purchase_print_sku");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @AutoLog(value = "t_purchase_print_sku-导入excel",operateType=5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TPurchasePrintSku.class);
    }

}
